using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace DocumentCreationSystem.Services.ReasoningEngine
{
    /// <summary>
    /// 推理引擎服务扩展
    /// </summary>
    public static class ReasoningEngineExtensions
    {
        /// <summary>
        /// 注册推理引擎服务
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddReasoningEngine(this IServiceCollection services)
        {
            services.AddSingleton<IReasoningEngine, ReasoningEngine>();
            services.AddSingleton<IReasoningEngineInitializer, ReasoningEngineInitializer>();
            
            return services;
        }

        /// <summary>
        /// 配置推理引擎
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="configureOptions">配置选项</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddReasoningEngine(this IServiceCollection services, 
            Action<ReasoningEngineOptions> configureOptions)
        {
            services.Configure(configureOptions);
            services.AddSingleton<IReasoningEngine, ReasoningEngine>();
            services.AddSingleton<IReasoningEngineInitializer, ReasoningEngineInitializer>();
            
            return services;
        }
    }

    /// <summary>
    /// 推理引擎配置选项
    /// </summary>
    public class ReasoningEngineOptions
    {
        /// <summary>
        /// 默认最大推理深度
        /// </summary>
        public int DefaultMaxDepth { get; set; } = 10;

        /// <summary>
        /// 默认最小置信度阈值
        /// </summary>
        public double DefaultMinConfidence { get; set; } = 0.5;

        /// <summary>
        /// 默认推理超时时间（毫秒）
        /// </summary>
        public int DefaultTimeoutMs { get; set; } = 30000;

        /// <summary>
        /// 是否启用自动清理过期事实
        /// </summary>
        public bool EnableAutoCleanup { get; set; } = true;

        /// <summary>
        /// 自动清理间隔（分钟）
        /// </summary>
        public int AutoCleanupIntervalMinutes { get; set; } = 60;

        /// <summary>
        /// 最大事实数量限制
        /// </summary>
        public int MaxFactsLimit { get; set; } = 10000;

        /// <summary>
        /// 最大规则数量限制
        /// </summary>
        public int MaxRulesLimit { get; set; } = 1000;

        /// <summary>
        /// 是否启用推理缓存
        /// </summary>
        public bool EnableReasoningCache { get; set; } = true;

        /// <summary>
        /// 推理缓存大小
        /// </summary>
        public int ReasoningCacheSize { get; set; } = 1000;

        /// <summary>
        /// 是否启用详细日志
        /// </summary>
        public bool EnableVerboseLogging { get; set; } = false;

        /// <summary>
        /// 知识库持久化路径
        /// </summary>
        public string? KnowledgeBasePath { get; set; }

        /// <summary>
        /// 是否在启动时自动加载知识库
        /// </summary>
        public bool AutoLoadKnowledgeBase { get; set; } = false;

        /// <summary>
        /// 是否在关闭时自动保存知识库
        /// </summary>
        public bool AutoSaveKnowledgeBase { get; set; } = true;
    }

    /// <summary>
    /// 推理引擎初始化器接口
    /// </summary>
    public interface IReasoningEngineInitializer
    {
        /// <summary>
        /// 初始化推理引擎
        /// </summary>
        /// <param name="reasoningEngine">推理引擎实例</param>
        /// <returns>初始化任务</returns>
        Task InitializeAsync(IReasoningEngine reasoningEngine);

        /// <summary>
        /// 加载默认规则
        /// </summary>
        /// <param name="reasoningEngine">推理引擎实例</param>
        /// <returns>加载任务</returns>
        Task LoadDefaultRulesAsync(IReasoningEngine reasoningEngine);

        /// <summary>
        /// 加载示例事实
        /// </summary>
        /// <param name="reasoningEngine">推理引擎实例</param>
        /// <returns>加载任务</returns>
        Task LoadExampleFactsAsync(IReasoningEngine reasoningEngine);
    }

    /// <summary>
    /// 推理引擎初始化器实现
    /// </summary>
    public class ReasoningEngineInitializer : IReasoningEngineInitializer
    {
        private readonly ILogger<ReasoningEngineInitializer> _logger;

        public ReasoningEngineInitializer(ILogger<ReasoningEngineInitializer> logger)
        {
            _logger = logger;
        }

        public async Task InitializeAsync(IReasoningEngine reasoningEngine)
        {
            try
            {
                _logger.LogInformation("开始初始化推理引擎...");

                // 加载默认规则
                await LoadDefaultRulesAsync(reasoningEngine);

                // 加载示例事实
                await LoadExampleFactsAsync(reasoningEngine);

                _logger.LogInformation("推理引擎初始化完成");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "推理引擎初始化失败");
                throw;
            }
        }

        public async Task LoadDefaultRulesAsync(IReasoningEngine reasoningEngine)
        {
            try
            {
                var defaultRules = CreateDefaultRules();
                await reasoningEngine.AddRulesAsync(defaultRules);

                _logger.LogInformation($"已加载 {defaultRules.Count} 个默认规则");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载默认规则失败");
                throw;
            }
        }

        public async Task LoadExampleFactsAsync(IReasoningEngine reasoningEngine)
        {
            try
            {
                var exampleFacts = CreateExampleFacts();
                await reasoningEngine.AddFactsAsync(exampleFacts);

                _logger.LogInformation($"已加载 {exampleFacts.Count} 个示例事实");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载示例事实失败");
                throw;
            }
        }

        private List<Models.Reasoning.ReasoningRule> CreateDefaultRules()
        {
            var rules = new List<Models.Reasoning.ReasoningRule>();

            // 规则1: 传递性规则
            rules.Add(new Models.Reasoning.ReasoningRule
            {
                Id = "rule_transitivity",
                Name = "传递性规则",
                Description = "如果A关联B，B关联C，则A关联C",
                Priority = 1,
                Confidence = 0.9,
                Type = Models.Reasoning.RuleType.Deductive,
                Conditions = new List<Models.Reasoning.RuleCondition>
                {
                    new Models.Reasoning.RuleCondition
                    {
                        Type = Models.Reasoning.ConditionType.FactMatch,
                        Pattern = new Models.Reasoning.FactPattern
                        {
                            PredicatePattern = "关联",
                            UseRegex = false,
                            IgnoreCase = true
                        }
                    }
                },
                Conclusions = new List<Models.Reasoning.RuleConclusion>
                {
                    new Models.Reasoning.RuleConclusion
                    {
                        Type = Models.Reasoning.ConclusionType.AddFact,
                        Confidence = 0.8
                    }
                },
                Tags = new List<string> { "传递性", "基础逻辑", "关系推理" }
            });

            // 规则2: 类型继承规则
            rules.Add(new Models.Reasoning.ReasoningRule
            {
                Id = "rule_inheritance",
                Name = "类型继承规则",
                Description = "如果A是B的实例，B具有属性P，则A也具有属性P",
                Priority = 2,
                Confidence = 0.95,
                Type = Models.Reasoning.RuleType.Deductive,
                Conditions = new List<Models.Reasoning.RuleCondition>
                {
                    new Models.Reasoning.RuleCondition
                    {
                        Type = Models.Reasoning.ConditionType.FactMatch,
                        Pattern = new Models.Reasoning.FactPattern
                        {
                            PredicatePattern = "是",
                            UseRegex = false,
                            IgnoreCase = true
                        }
                    },
                    new Models.Reasoning.RuleCondition
                    {
                        Type = Models.Reasoning.ConditionType.FactMatch,
                        Pattern = new Models.Reasoning.FactPattern
                        {
                            PredicatePattern = "具有",
                            UseRegex = false,
                            IgnoreCase = true
                        }
                    }
                },
                Conclusions = new List<Models.Reasoning.RuleConclusion>
                {
                    new Models.Reasoning.RuleConclusion
                    {
                        Type = Models.Reasoning.ConclusionType.AddFact,
                        Confidence = 0.9
                    }
                },
                Tags = new List<string> { "继承", "类型系统", "属性推理" }
            });

            // 规则3: 因果关系规则
            rules.Add(new Models.Reasoning.ReasoningRule
            {
                Id = "rule_causality",
                Name = "因果关系规则",
                Description = "如果A导致B，B导致C，则A可能导致C",
                Priority = 3,
                Confidence = 0.7,
                Type = Models.Reasoning.RuleType.Probabilistic,
                Conditions = new List<Models.Reasoning.RuleCondition>
                {
                    new Models.Reasoning.RuleCondition
                    {
                        Type = Models.Reasoning.ConditionType.FactMatch,
                        Pattern = new Models.Reasoning.FactPattern
                        {
                            PredicatePattern = "导致",
                            UseRegex = false,
                            IgnoreCase = true
                        }
                    }
                },
                Conclusions = new List<Models.Reasoning.RuleConclusion>
                {
                    new Models.Reasoning.RuleConclusion
                    {
                        Type = Models.Reasoning.ConclusionType.AddFact,
                        Confidence = 0.6
                    }
                },
                Tags = new List<string> { "因果关系", "概率推理", "间接影响" }
            });

            // 规则4: 否定规则
            rules.Add(new Models.Reasoning.ReasoningRule
            {
                Id = "rule_negation",
                Name = "否定规则",
                Description = "如果A不是B，且B是C的唯一可能，则A不是C",
                Priority = 4,
                Confidence = 0.85,
                Type = Models.Reasoning.RuleType.Deductive,
                Conditions = new List<Models.Reasoning.RuleCondition>
                {
                    new Models.Reasoning.RuleCondition
                    {
                        Type = Models.Reasoning.ConditionType.FactMatch,
                        Pattern = new Models.Reasoning.FactPattern
                        {
                            PredicatePattern = "不是",
                            UseRegex = false,
                            IgnoreCase = true
                        }
                    }
                },
                Conclusions = new List<Models.Reasoning.RuleConclusion>
                {
                    new Models.Reasoning.RuleConclusion
                    {
                        Type = Models.Reasoning.ConclusionType.AddFact,
                        Confidence = 0.8
                    }
                },
                Tags = new List<string> { "否定", "排除推理", "逻辑否定" }
            });

            // 规则5: 时间顺序规则
            rules.Add(new Models.Reasoning.ReasoningRule
            {
                Id = "rule_temporal",
                Name = "时间顺序规则",
                Description = "如果A在B之前发生，B在C之前发生，则A在C之前发生",
                Priority = 5,
                Confidence = 1.0,
                Type = Models.Reasoning.RuleType.Deductive,
                Conditions = new List<Models.Reasoning.RuleCondition>
                {
                    new Models.Reasoning.RuleCondition
                    {
                        Type = Models.Reasoning.ConditionType.FactMatch,
                        Pattern = new Models.Reasoning.FactPattern
                        {
                            PredicatePattern = "在.*之前",
                            UseRegex = true,
                            IgnoreCase = true
                        }
                    }
                },
                Conclusions = new List<Models.Reasoning.RuleConclusion>
                {
                    new Models.Reasoning.RuleConclusion
                    {
                        Type = Models.Reasoning.ConclusionType.AddFact,
                        Confidence = 1.0
                    }
                },
                Tags = new List<string> { "时间", "顺序", "传递性" }
            });

            return rules;
        }

        private List<Models.Reasoning.ReasoningFact> CreateExampleFacts()
        {
            var facts = new List<Models.Reasoning.ReasoningFact>();

            // 基础事实
            facts.Add(new Models.Reasoning.ReasoningFact
            {
                Subject = "苏格拉底",
                Predicate = "是",
                Object = "人",
                Confidence = 1.0,
                Type = Models.Reasoning.FactType.Assertion,
                Source = "示例数据",
                Tags = new List<string> { "哲学", "人物", "古希腊" }
            });

            facts.Add(new Models.Reasoning.ReasoningFact
            {
                Subject = "人",
                Predicate = "是",
                Object = "有理性的动物",
                Confidence = 0.95,
                Type = Models.Reasoning.FactType.Assertion,
                Source = "示例数据",
                Tags = new List<string> { "定义", "人类", "理性" }
            });

            facts.Add(new Models.Reasoning.ReasoningFact
            {
                Subject = "有理性的动物",
                Predicate = "具有",
                Object = "思考能力",
                Confidence = 0.9,
                Type = Models.Reasoning.FactType.Assertion,
                Source = "示例数据",
                Tags = new List<string> { "能力", "思考", "理性" }
            });

            // 技术相关事实
            facts.Add(new Models.Reasoning.ReasoningFact
            {
                Subject = "AI",
                Predicate = "是",
                Object = "人工智能",
                Confidence = 1.0,
                Type = Models.Reasoning.FactType.Assertion,
                Source = "示例数据",
                Tags = new List<string> { "技术", "AI", "定义" }
            });

            facts.Add(new Models.Reasoning.ReasoningFact
            {
                Subject = "人工智能",
                Predicate = "具有",
                Object = "学习能力",
                Confidence = 0.8,
                Type = Models.Reasoning.FactType.Assertion,
                Source = "示例数据",
                Tags = new List<string> { "AI", "学习", "能力" }
            });

            facts.Add(new Models.Reasoning.ReasoningFact
            {
                Subject = "机器学习",
                Predicate = "是",
                Object = "人工智能的分支",
                Confidence = 0.95,
                Type = Models.Reasoning.FactType.Assertion,
                Source = "示例数据",
                Tags = new List<string> { "机器学习", "AI", "分支" }
            });

            // 因果关系事实
            facts.Add(new Models.Reasoning.ReasoningFact
            {
                Subject = "学习",
                Predicate = "导致",
                Object = "知识增长",
                Confidence = 0.9,
                Type = Models.Reasoning.FactType.Assertion,
                Source = "示例数据",
                Tags = new List<string> { "学习", "知识", "因果" }
            });

            facts.Add(new Models.Reasoning.ReasoningFact
            {
                Subject = "知识增长",
                Predicate = "导致",
                Object = "能力提升",
                Confidence = 0.85,
                Type = Models.Reasoning.FactType.Assertion,
                Source = "示例数据",
                Tags = new List<string> { "知识", "能力", "因果" }
            });

            // 时间相关事实
            facts.Add(new Models.Reasoning.ReasoningFact
            {
                Subject = "数据收集",
                Predicate = "在训练之前",
                Object = "发生",
                Confidence = 1.0,
                Type = Models.Reasoning.FactType.Assertion,
                Source = "示例数据",
                Tags = new List<string> { "时间", "数据", "训练" }
            });

            facts.Add(new Models.Reasoning.ReasoningFact
            {
                Subject = "训练",
                Predicate = "在部署之前",
                Object = "发生",
                Confidence = 1.0,
                Type = Models.Reasoning.FactType.Assertion,
                Source = "示例数据",
                Tags = new List<string> { "时间", "训练", "部署" }
            });

            return facts;
        }
    }
}
